<?php
/**
 * 管理员后台控制器
 * 
 * @version $Id: Report.php 469 2012-10-31 08:24:41Z linsir123 $
 */
class controllerReport extends AdminController 
{
	/**
	 * 登录并且获取授权
	 */
	function actionIndex()
	{
		if (Request::isPost()) {
			@session_start();
			if ( ! isset($_SESSION['top']) || empty($_SESSION['top'])) {
				$url = trim($_POST['url']);
				$data = $_SESSION['top'] = $this->getCallback($url);
			} else 
				$data = $_SESSION['top'];
				
			///
			$appkey = $data['top_appkey'];
			$sessionKey = $data['top_session'];
			if ( ! empty($appkey) && ! empty($sessionKey)) {
				M::topSender()->login($sessionKey);
				
				///
				$startDate = trim($_POST['start_date']);
				$endDate = trim($_POST['end_date']);
				if (lpString::isDate($startDate) && lpString::isDate($endDate)) {
					$startDate = strtotime($startDate);
					$endDate = strtotime($endDate);
					if ($startDate < $endDate) {
						
						/* */
						MA::report()->fetch($startDate, $endDate);
						
					} else 
						$this->tipMsg('开始时间不能大于结束时间', 1, 0, 'report');
						
				} else 
					$this->tipMsg('日期格式有误', 1, 0, 'report');
					
			} else 
				$this->tipMsg('授权失败', 1, 0, 'report');
			
		} else {
			View::display('report/index');
			View::assignSet(array(
				'title' => '淘宝报表',
				'session' => ! empty($_SESSION['top']),
				'loginUrl' => $this->getLoginUrl(),
				'date' => array(
					'start'=>date('Y-m-d', strtotime("-1 day")),
					'end'=>date('Y-m-d')
				)
			));
		}
	}
	
	/**
	 * 登录地址
	 */
	function getLoginUrl()
	{
		$conf = App::O('taobaoke.app');
		///
		return "http://container.api.taobao.com/container?appkey={$conf[0]}&encode=utf-8";
	}
	
	/**
	 * 处理授权结果
	 */
	function getCallback($url)
	{
		$tmp = parse_url(urldecode($url));
		parse_str($tmp['query'], $data);
		return $data;
	}
}
